package cn.edu.neu.lab603.cloudeval.strategy.policy

import java.util.concurrent.atomic.AtomicLong

import cn.edu.neu.lab603.cloudeval.entity.DataCenter

/** 对 HostSelectionPolicyUtilizationBase 进行转换。
  *
  * Created by yfwz100 on 2016/11/10.
  */
object ReAllocationTimePolicyUtilizationBase {

  import MigrationDef._

  def apply(hostSelectionPolicy: HostSelectionPolicyUtilizationBase, checkPeriod: Int = 25): ReAllocationTimePolicy =
    new RATPWrapper(hostSelectionPolicy, checkPeriod)

  private class RATPWrapper(hsp: HostSelectionPolicyUtilizationBase, checkPeriod: Int) extends ReAllocationTimePolicy {

    // 时钟周期计数器
    val clockCounter = new AtomicLong

    override def isTimeForReallocation(implicit dataCenter: DataCenter): Boolean =
      if (clockCounter.incrementAndGet() % checkPeriod == 0)
        dataCenter.getRunningHost.exists { h =>
          h.isIdle || hsp.isOverloadHost(h)
        }
      else false

    override def toString: String = s"$hsp"
  }
}
